package com.gxuwz.zjh.mxbbx.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.zjh.mxbbx.entity.*;
import com.gxuwz.zjh.mxbbx.service.*;
import org.apache.ibatis.annotations.Param;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import sun.security.krb5.internal.ccache.CCacheInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 慢性病报销信息表 前端控制器
 * </p>
 *
 * @author zhangjiahui
 * @since 2021-03-21
 */
@RestController
@RequestMapping("/mxbbx/reim")
public class ChronicReimController {

    @Autowired
    private IChronicReimService iChronicReimService;
    @Autowired
    private IChronicCardService iChronicCardService;
    @Autowired
    private IFamiliesService iFamiliesService;
    @Autowired
    private IFamilyService iFamilyService;
    @Autowired
    private IPolicyService iPolicyService;
    @Autowired
    private IPaysService iPaysService;
    @Autowired
    private IRegionService iRegionService;
    @Autowired
    private IChronicService iChronicService;

    /**
     * 查询全部信息
     * @param modelAndView
     * @param request
     * @param response
     * @return
     */
    @Pointcut
    @RequestMapping(value = "/findReimAll")
    public ModelAndView findReimAll(ModelAndView modelAndView, Page page, Integer pageNumber,
                                    HttpServletRequest request, HttpServletResponse response,
                                    @Param("invoice") String invoice,
                                    @Param("chronic") String chronic,
                                    @Param("region") String region) {
        // 可以通过 wrapper 进行筛选!!!
        QueryWrapper<ChronicReim> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("invoice");
        // 进行模糊查询!!!
        if(region != null && region != ""){
            Family family = new Family();
            List<Family> familyList;
            switch (region.length()){
                case 6:
                    family.setLevelId(region);
                    familyList = iFamilyService.findFamilyByRegion(family);
                    for(Family family1: familyList){
                        wrapper.eq("number", family1.getNumber()).or();
                    }
                    break;
                case 8:
                    family.setShipId(region);
                    familyList = iFamilyService.findFamilyByRegion(family);
                    for(Family family1: familyList){
                        wrapper.eq("number", family1.getNumber()).or();
                    }
                    break;
                case 10:
                    family.setVillageId(region);
                    familyList = iFamilyService.findFamilyByRegion(family);
                    for(Family family1: familyList){
                        wrapper.eq("number", family1.getNumber()).or();
                    }
                    break;
                case 12:
                    family.setGroupId(region);
                    familyList = iFamilyService.findFamilyByRegion(family);
                    for(Family family1: familyList){
                        wrapper.eq("number", family1.getNumber()).or();
                    }
                    break;
            }
            request.getSession().setAttribute("region", region);
        }else {
            request.getSession().setAttribute("region", "");
        }
        if(chronic != null && chronic != ""){
            wrapper.eq("chronic_id", chronic);
            request.getSession().setAttribute("chronic", chronic);
        }else {
            request.getSession().setAttribute("chronic", "");
        }
        if(invoice != null && invoice != ""){
            wrapper.like("invoice", invoice);
            request.getSession().setAttribute("invoice", invoice);
        }else {
            request.getSession().setAttribute("invoice", "");
        }
        // Current,页码 + Size,每页条数
        if(pageNumber == null){
            page.setCurrent(1);
        }else {
            page.setCurrent((long)pageNumber);
        }
        // 默认每页6行数据！
        page.setSize(6);
        // 调用分页查询方法！!
        IPage<ChronicReim> chronicReimIPage = iChronicReimService.selectChronicReimPage(page, wrapper);
        HttpSession session = request.getSession();
        // 存放一个数组用来让foreach遍历
        int[] pagesList = new int[(int)chronicReimIPage.getPages()];
        for(int i=0; i< (int)chronicReimIPage.getPages(); i++){
            pagesList[i] = i+1;
        }
        session.setAttribute("pagesList", pagesList);
        // 存放page，内有当前页数
        session.setAttribute("page", page);
        System.out.println("总条数"+chronicReimIPage.getTotal());
        System.out.println("总页数"+chronicReimIPage.getPages());
        // 存放总页数
        session.setAttribute("pages", (int)chronicReimIPage.getPages());
        List<ChronicReim> chronicReimList = chronicReimIPage.getRecords();
        System.out.println("chronicReimList = "+chronicReimList);
        modelAndView.addObject("chronicReimList", chronicReimList);

        // 查询身份证号对应的人员姓名
        List<Families> familiesList = iFamiliesService.findFamiliesAll();
        modelAndView.addObject("familiesList", familiesList);

        // 通过iRegionService获取对应的地址信息
        List<Region> regionList = iRegionService.findRegionAll();
        modelAndView.addObject("regionList", regionList);

        // 查询全部慢性病
        List<Chronic> chronicList = iChronicService.findChronicAll();
        modelAndView.addObject("chronicList", chronicList);

        modelAndView.setViewName("reim/reim_list");
        return modelAndView;
    }


    /**
     * 跳转进入新增界面
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/insertReim")
    public ModelAndView insertReim(ModelAndView modelAndView, HttpServletRequest request) {
        // 查询全部慢性病
        List<Chronic> chronicList = iChronicService.findChronicAll();
        modelAndView.addObject("chronicList", chronicList);

        modelAndView.setViewName("reim/reim_insert");
        return modelAndView;
    }

    /**
     * 添加信息
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/addReim")
    public ModelAndView addReim(ModelAndView modelAndView, ChronicReim chronicReim, HttpServletRequest request,
                                @Param("time") String time) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time1 = null;
        if(time != null && time != ""){
            Date time2 = formatter.parse(time);
            time1 = formatter.format(time2);
        }
        chronicReim.setTime(time1);

        ChronicReim chronicReim1 = iChronicReimService.findChronicReimById(chronicReim);
        if(chronicReim1 == null){
            iChronicReimService.addChronicReim(chronicReim);
            request.setAttribute("result1", "addTrue");
        }else {
            request.setAttribute("result1", "addFalse");
        }
        modelAndView.setViewName("reim/reim_list");
        return modelAndView;
    }

    /**
     * 跳转进入修改界面
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/updateReim")
    public ModelAndView updateReim(ModelAndView modelAndView, String invoice) {
        ChronicReim chronicReim = new ChronicReim();
        chronicReim.setInvoice(invoice);
        ChronicReim chronicReim1 = iChronicReimService.findChronicReimById(chronicReim);
        modelAndView.addObject("chronicReim", chronicReim1);

        // 查询全部慢性病
        List<Chronic> chronicList = iChronicService.findChronicAll();
        modelAndView.addObject("chronicList", chronicList);

        modelAndView.setViewName("reim/reim_update");
        return modelAndView;
    }

    /**
     * 修改信息
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/editReim")
    public ModelAndView editReim(ModelAndView modelAndView, ChronicReim chronicReim, HttpServletRequest request,
                                 @Param("time") String time) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time1 = null;
        if(time != null && time != ""){
            Date time2 = formatter.parse(time);
            time1 = formatter.format(time2);
        }
        chronicReim.setTime(time1);

        iChronicReimService.updateChronicReimById(chronicReim);
        request.setAttribute("result2", "editTrue");
        modelAndView.setViewName("reim/reim_list");
        return modelAndView;
    }

    /**
     * 删除信息
     * @return
     */
    @RequestMapping(value = "/deleteReimById")
    public ModelAndView deleteReimById(ModelAndView modelAndView, HttpServletRequest request, String invoice) {
        ChronicReim chronicReim = new ChronicReim();
        chronicReim.setInvoice(invoice);
        iChronicReimService.deleteChronicReimById(chronicReim);
        request.setAttribute("result3", "deleteTrue");
        modelAndView.setViewName("reim/reim_list");
        return modelAndView;
    }

    /**
     * 跳转进入报销界面时的判断
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/reimEdit")
    public ModelAndView reimEdit(ModelAndView modelAndView, HttpServletRequest request,
                                   @Param("cardId") String cardId) throws ParseException {
        ChronicCard chronicCard = new ChronicCard();
        chronicCard.setCardId(cardId);
        chronicCard = iChronicCardService.findChronicCardById(chronicCard);
        System.out.println("reim chronicCard = " + chronicCard);
        Families families = new Families();
        families.setNongheId(chronicCard.getCardId());
        families = iFamiliesService.findFamiliesByNonghe(families);

        // 判断当前慢性病证是否存在时间等信息，判断完整性
        if(chronicCard.getChronicStartTime() == null || chronicCard.getChronicEndTime() == null){
            request.setAttribute("card_none", "no");
            modelAndView.setViewName("card/card_list");
            return modelAndView;
        }

        // 判断当前时间是否在慢性病证的规定时间中
        // 获取当前时间，并进行格式化
        SimpleDateFormat formant = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String nowTime = formant.format(new Date());
        Date nowTimes = formant.parse(nowTime);
        System.out.println("nowTimes = " + nowTimes);
        List<ChronicCard> chronicCardList = iChronicCardService.nowTimesByCard(nowTimes);
        int tw = 0;
        for(int t=0; t<chronicCardList.size(); t++){
            // 判断筛选符合条件的数据中，当前慢性病证是否在其中
            if(chronicCardList.get(t).getCardId().equals(chronicCard.getCardId())){
                tw = 1;
                break;
            }
        }
        // 若不存在，则返回进行提示
        if(tw == 0){
            request.setAttribute("card_none", "none");
            modelAndView.setViewName("card/card_list");
            return modelAndView;
        }

        // 对该用户进行是否缴费判断
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        Pays pays = new Pays();
        pays.setFamilyId(families.getFamilyId());
        pays.setYear(formatter.format(new Date()));
        pays = iPaysService.findPaysByFamily(pays);
        System.out.println("pays = " + pays);
        if(pays != null){
            // 判断家庭缴费人员是否为空
            if(pays.getFamilyName() == null){
                // 该家庭缴费人员为空
                request.setAttribute("card_person", "none");
                modelAndView.setViewName("card/card_list");
                return modelAndView;
            }else {
                // 该家庭存在缴费人员
                String[] names = pays.getFamilyName().split(",");
                System.out.println("names = " + names);
                int num = 0;
                // 判断该用户是否是该家庭的缴费人员
                for(int i=0; i<names.length; i++){
                    if(names[i].equals(chronicCard.getName())){
                        num = 1;
                        break;
                    }
                }
                if(num == 0){
                    // 该用户未在家庭中参与缴费
                    request.setAttribute("card_person", "none");
                    modelAndView.setViewName("card/card_list");
                    return modelAndView;
                }
            }
        }else {
            // 该家庭尚未开启本年度缴费
            request.setAttribute("pay_why", "none");
            modelAndView.setViewName("family/family_list");
            return modelAndView;
        }

        System.out.println("reim families = " + families);
        ChronicReim chronicReim = new ChronicReim();
        chronicReim.setNumber(families.getNumber());

        // 获取当年的报销方案
        Policy policy = new Policy();
        policy.setYear(formatter.format(new Date()));
        policy = iPolicyService.findPolicyByYear(policy);

        // 查询该身份证的全部慢性病报销信息，然后进行当前年份筛查
        List<ChronicReim> chronicReimList = iChronicReimService.findChronicReimByNumber(chronicReim);
        ChronicReim chronicReims = null;
        System.out.println("reim chronicReimList = " + chronicReimList);
        for(int i=0; i<chronicReimList.size(); i++){
            String[] times = chronicReimList.get(i).getTime().split("-");
            System.out.println("year = " + times[0]);
            if(times[0].equals(formatter.format(new Date()))){
                chronicReims = chronicReimList.get(i);
                break;
            }
        }
        System.out.println("reim chronicReim = " + chronicReims);

        // 查询全部慢性病
        List<Chronic> chronicList = iChronicService.findChronicAll();
        modelAndView.addObject("chronicList", chronicList);

        // 报销方案的判断
        if(policy == null){
            request.setAttribute("policy_year", "none");
            modelAndView.setViewName("policy/policy_list");
            return modelAndView;
        }else {
            // 判断是否存在对应报销记录
            if(chronicReims == null){
                // 进行编号生成
                ChronicReim chronicReim1 = new ChronicReim();
                System.out.println(" String 1 = " + families.getNumber().substring(6));
                System.out.println(" String 2 = " + policy.getYear());
                System.out.println(" String 3 = " + families.getNumber().substring(6) + policy.getYear());
                chronicReim1.setInvoice(families.getNumber().substring(6) + policy.getYear());
                chronicReim1.setWantPay(0);
                chronicReim1.setNumber(families.getNumber());
                chronicReim1.setTime(null);
                chronicReim1.setPerson(null);
                // 默认为未审批
                chronicReim1.setStart(0);
                double money = Double.valueOf(policy.getCappLine());
                modelAndView.addObject("chronicReim", chronicReim1);
                modelAndView.addObject("money", money);
                System.out.println("chronicReim = " + chronicReim1);
                System.out.println("money = " + money);
                modelAndView.setViewName("reim/reim_edit");
                return modelAndView;
            }else {
                double money = Double.valueOf(policy.getCappLine()) - chronicReims.getPayAll();
                modelAndView.addObject("chronicReim", chronicReims);
                modelAndView.addObject("money", money);
                System.out.println("chronicReim = " + chronicReims);
                System.out.println("money = " + money);
                modelAndView.setViewName("reim/reim_edit");
                return modelAndView;
            }
        }

    }

    /**
     * 报销
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/reimEditMent")
    public ModelAndView reimEditMent(ModelAndView modelAndView, HttpServletRequest request, ChronicReim chronicReim,
                                     @Param("time") String time,
                                     @Param("money") String money) throws ParseException {
        // 时间格式化
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time1 = null;
        if(time != null && time != ""){
            Date time2 = formatter.parse(time);
            time1 = formatter.format(time2);
        }
        chronicReim.setTime(time1);

        // 判断报销疾病是否和慢性病证是否对应
        // 通过身份证号获取用户信息
        Families families = new Families();
        families.setNumber(chronicReim.getNumber());
        families = iFamiliesService.findFamiliesByNumber(families);
        // 通过农合证号获取慢性病证信息
        ChronicCard chronicCard = new ChronicCard();
        chronicCard.setCardId(families.getNongheId());
        chronicCard = iChronicCardService.findChronicCardById(chronicCard);
        System.out.println("chronicReim.getChronicId() = " + chronicReim.getChronicId());
        System.out.println("chronicCard.getChronicId() = " + chronicCard.getChronicId());
        if(!chronicReim.getChronicId().equals(chronicCard.getChronicId())){
            request.setAttribute("chronic_no", "no");
            modelAndView.setViewName("chronic/chronic_list");
            return modelAndView;
        }

        // 查询本年度的报销比例,并进行计算
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy");
        Policy policy = new Policy();
        policy.setYear(formatter2.format(new Date()));
        policy = iPolicyService.findPolicyByYear(policy);
        // 报销比例
        double radio = Double.valueOf(policy.getReimRatio());

        // 计算预计的报销金额是否超出预期
        // 医院花费
        double wantMoney = chronicReim.getWantPay();
        // 计算报销后的金额
        double nowMoney = wantMoney * radio;

        // 本年度封顶线
        double maxMoney = Double.valueOf(policy.getCappLine());
        // 剩余报销金额
        double endMoney = maxMoney - chronicReim.getPayAll();

        // 判断当前金额是否超出剩余报销金额
        // 若小于等于则予以报销
        if(nowMoney <= endMoney){
            // 修改实际报销金额
            chronicReim.setNowPay(nowMoney);
            // 修改报销后报销总金额
            chronicReim.setPayAll(nowMoney + chronicReim.getPayAll());
            // 添加/修改记录
            // 判断是否存在记录
            if(iChronicReimService.findChronicReimById(chronicReim) != null){
                // 修改记录
                iChronicReimService.updateChronicReimById(chronicReim);
            }else {
                // 新增记录
                iChronicReimService.addChronicReim(chronicReim);
            }
            request.setAttribute("reim_radio", "yes");
            modelAndView.setViewName("reim/reim_list");
            return modelAndView;
        }else {
            // 如果超出剩余报销金额
            // 修改实际报销金额
            chronicReim.setWantPay(endMoney);
            // 修改报销后报销总金额
            chronicReim.setNowPay(nowMoney + endMoney);
            // 添加/修改记录
            // 判断是否存在记录
            if(iChronicReimService.findChronicReimById(chronicReim) != null){
                // 修改记录
                iChronicReimService.updateChronicReimById(chronicReim);
            }else {
                // 新增记录
                iChronicReimService.addChronicReim(chronicReim);
            }
            request.setAttribute("reim_radio", "none");
            modelAndView.setViewName("reim/reim_list");
            return modelAndView;
        }

    }

    @ResponseBody
    @RequestMapping("/getcountbydisName")
    public  List<Echarts> getcountbydisName(HttpServletRequest request) throws IOException {

        List<ChronicReim> chronicReimList = new ArrayList<>();
        List<ChronicReim> Chronics = new ArrayList<>();
        List<Chronic> chronicList = new ArrayList<>();

        if(request.getSession().getAttribute("chronic") == null || request.getSession().getAttribute("chronic") == ""){
            chronicReimList = iChronicReimService.findChronicReimAll();
        }else {
            String chronicId = (String) request.getSession().getAttribute("chronic");
            ChronicReim chronicReim = new ChronicReim();
            chronicReim.setChronicId(chronicId);
            chronicReimList = iChronicReimService.findChronicReimByChronic(chronicReim);
        }
        Chronics = iChronicReimService.findChronicReimByChronicId();
        chronicList = iChronicService.findChronicAll();


        int[] mun = new int[Chronics.size()];
        String[] numName = new String[Chronics.size()];
        for (int i=0; i<chronicReimList.size(); i++){
            chronicReimList.get(i).getChronicId();
            System.out.println(chronicReimList.get(i).getChronicId());
            for (int j=0; j<Chronics.size(); j++){
                Chronics.get(j).getChronicId();
                System.out.println(Chronics.get(j).getChronicId());
                numName[j]=Chronics.get(j).getChronicId();
                if(chronicReimList.get(i).getChronicId().equals(Chronics.get(j).getChronicId())){
                    mun[j]++;
                }
            }
        }
        for(int i: mun){
            System.out.println("i = " + i);
        }
        for(String name: numName){
            System.out.println("name = " + name);
        }

        List<Echarts> nums = new ArrayList<>(numName.length);
        for(int m=0; m<numName.length; m++){
            Echarts num = new Echarts();
            for(Chronic chronic:chronicList){
                if(chronic.getChronicId().equals(numName[m])){
                    num.setName(chronic.getChronicName());
                }
            }
            num.setValue(mun[m]);
            nums.add(num);
        }

        return nums;

    }

    @ResponseBody
    @RequestMapping("/getcountbydisName2")
    public  List<Echarts> getcountbydisName2(HttpServletRequest request) throws IOException {

        List<Echarts> echartsList = new ArrayList<>();

        String region = (String) request.getSession().getAttribute("region");

        if(region != null && region != ""){
            Family family = new Family();
            switch (region.length()){
                case 6:
                    family.setLevelId(region);
                    echartsList = iChronicReimService.findEcharts(family);
                    break;
                case 8:
                    family.setShipId(region);
                    echartsList = iChronicReimService.findEcharts(family);
                    break;
                case 10:
                    family.setVillageId(region);
                    echartsList = iChronicReimService.findEcharts(family);
                    break;
                case 12:
                    family.setGroupId(region);
                    echartsList = iChronicReimService.findEcharts(family);
                    break;
            }
        }else {
            echartsList = iChronicReimService.findEcharts(null);
        }

        List<Echarts> fatherOne = new ArrayList<>();
        List<Echarts> fatherTwo = new ArrayList<>();
        List<Echarts> fatherThree = new ArrayList<>();
        List<Echarts> fatherFour = new ArrayList<>();

        for (Echarts echarts :echartsList) {
            if (echarts.getEid().length() == 6) {
                fatherOne.add(echarts);
            }else if (echarts.getEid().length() == 8){
                fatherTwo.add(echarts);
            }else if (echarts.getEid().length() == 10){
                fatherThree.add(echarts);
            }else if (echarts.getEid().length() == 12){
                fatherFour.add(echarts);
            }
        }


        for(Echarts echarts: fatherThree){
            List<Echarts> echartsList1 = new ArrayList<>();
            for(Echarts echarts2: fatherFour){
                if(echarts.getEid().equals(echarts2.getEid().substring(0,10))){
                    echartsList1.add(echarts2);
                }
            }
            echarts.setChildren(echartsList1);
        }
        System.out.println("fatherThree =" + fatherThree.toString());

        for(Echarts echarts: fatherTwo){
            List<Echarts> echartsList1 = new ArrayList<>();
            for(Echarts echarts2: fatherThree){
                if(echarts.getEid().equals(echarts2.getEid().substring(0,8))){
                    echartsList1.add(echarts2);
                }
            }
            echarts.setChildren(echartsList1);
        }
        System.out.println("fatherTwo =" + fatherTwo.toString());

        for(Echarts echarts: fatherOne){
            List<Echarts> echartsList1 = new ArrayList<>();
            for(Echarts echarts2: fatherTwo){
                if(echarts.getEid().equals(echarts2.getEid().substring(0,6))){
                    echartsList1.add(echarts2);
                }
            }
            echarts.setChildren(echartsList1);
        }
        System.out.println("fatherOne =" + fatherOne.toString());





//        for (Echarts echarts :echartsList){
//            if (echarts.getEid().length() == 8){
//                String fatherId = echarts.getEid().substring(0, 6);
//                System.out.println("fatherId = " + fatherId);
//                for (Echarts echarts2 :echartsList){
//                    if(fatherId.equals(echarts2.getEid())){
//                        List<Echarts> echartsList1 = new ArrayList<>();
//                        echartsList1.add(echarts);
//                        echarts2.setChildren(echartsList1);
//                    }
//                }
//
//            }else if (echarts.getEid().length() == 10){
//                String fatherId = echarts.getEid().substring(0, 8);
//                System.out.println("fatherId = " + fatherId);
//                for (Echarts echarts2 :echartsList){
//                    if(fatherId.equals(echarts2.getEid())){
//                        List<Echarts> echartsList1 = new ArrayList<>();
//                        echartsList1.add(echarts);
//                        echarts2.setChildren(echartsList1);
//                    }
//                }
//
//            }else if (echarts.getEid().length() == 12){
//                String fatherId = echarts.getEid().substring(0, 10);
//                System.out.println("fatherId = " + fatherId);
//                for (Echarts echarts2 :echartsList){
//                    if(fatherId.equals(echarts2.getEid())){
//                        List<Echarts> echartsList1 = new ArrayList<>();
//                        echartsList1.add(echarts);
//                        echarts2.setChildren(echartsList1);
//                    }
//
//                }
//
//            }
//        }

        System.out.println("echartsList =" + echartsList.toString());

        return fatherOne;

    }

}
